<html>
<head>


<script language="javascript" type="text/javascript" src="../arborjs/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="../arborjs/arbor.js" ></script>
<script language="javascript" type="text/javascript" src="../arborjs/graphics.js" ></script>
<script language="javascript" type="text/javascript" src="../arborjs/renderer.js" ></script>
<link href="../css/mycss.css" type="text/css" rel="stylesheet"/>

<link href="../css/colorbox.css" type="text/css" rel="stylesheet"/>
<script src="../colorbox/jquery.colorbox.js" type="text/javascript"></script>

<script src="../dropchecklist/jquery-ui-1.8.13.custom.min.js" type="text/javascript"></script>
<script src="../dropchecklist/ui.dropdownchecklist.js" type="text/javascript"></script>
<link href="../dropchecklist/jquery-ui-1.8.13.custom.css" type="text/css" rel="stylesheet"/>
<link href="../dropchecklist/ui.dropdownchecklist.themeroller.css" type="text/css" rel="stylesheet"/>


</head>
<body>
<?php
require_once('../../../config.php');

//yeu cau login,sau khi login tu dong chuyen sang trang chu
global $USER;
if ($USER->id == null){
    $SESSION->homepage = true;
    require_login($SITE);
}
if($SESSION->homepage){
    $SESSION->homepage = null;
    redirect( $CFG->wwwroot);
}

$id_bbsurvey = required_param('id_bbsurvey', PARAM_TEXT);

//khai bao cac bien can dung cho viec show course map
$dropcheck_items = '';
$node_data = '';
$child_data = '';
$parent_data = '';
$child_link_node = '';
$num_relation = '';
//node color status
$color_root = '#95cde5';
$color_bridge = '#85C247';
$color_leaf = 'orange';
$color_alone = 'gray';
$color_selected = '#0000FF';
$color_problem = 'red';
$color_edge = 'gray';

//lay danh sach subject
global $DB;
$sql = 'SELECT s.*
        FROM mdl_b_blackbox_survey as bb
        join mdl_subject as s on bb.id_program = s.program_id
        WHERE bb.id = '.$id_bbsurvey.' group by s.subject_id ORDER BY s.subject_name_vn';
$result = $DB->get_records_sql($sql);
foreach($result as $r) 
{   
    $link_node = "link_node['".$r->subject_id."'] = {};";
    //tao subject child node
    $sql_child = 'select cm.child_subject, s.subject_id, s.id
            from mdl_b_course_map as cm
            join mdl_subject as s on cm.child_subject = s.id
            where cm.id_bbsurvey = '.$id_bbsurvey.' and cm.parent_subject = '.$r->id.' and cm.child_subject != '.$r->id.' group by cm.child_subject';
    $child = $DB->get_records_sql($sql_child);
    $n_child = 0;
    $temp_child = '';
    $temp_link_node = '';
    foreach($child as $c)
    {
        //save child node
        $temp_child .= '"'.$c->subject_id.'"';
        $temp_link_node .= '"'.$r->subject_id.$c->subject_id.'"';
        if(++$n_child < count($child))
        {
            $temp_child .= ',';
            $temp_link_node .= ',';
        }
        //count number of relationtip of child node
        $num_rel = $DB->count_records('b_course_map', array('id_bbsurvey'=>$id_bbsurvey,'parent_subject'=>$r->id,'child_subject'=>$c->id));
        $num_relation .= "num_relation['".$r->subject_id.$c->subject_id."'] = ". $num_rel .";";
        
    }
    $child_data .= "child_data['".$r->subject_id."'] = [".$temp_child."];";
    $child_link_node .= "child_link_node['".$r->subject_id."'] = [".$temp_link_node."];";
    
    //save subject parent node
    $sql_parent = 'select cm.parent_subject, s.subject_id, s.id
            from mdl_b_course_map as cm
            join mdl_subject as s on cm.parent_subject = s.id
            where cm.id_bbsurvey = '.$id_bbsurvey.' and cm.child_subject = '.$r->id.' and cm.parent_subject != '.$r->id.' group by cm.parent_subject';
    $parent = $DB->get_records_sql($sql_parent);
    $n_parent = 0;
    $temp_parent = '';  
    foreach($parent as $p)
    {
        $temp_parent .= '"'.$p->subject_id.'"';
        if(++$n_parent < count($parent))
            $temp_parent .= ',';
    }
    $parent_data .= "parent_data['".$r->subject_id."'] = [".$temp_parent."];";
        
    //tao subject filter
    $temp_label = strtoupper(substr($r->subject_name_vn, 0,1));
    if($alphabet_label != $temp_label)
    {
        $alphabet_label = $temp_label;
        $dropcheck_items .= '</optgroup><optgroup label="'.$alphabet_label.'">';
    }
    //set color va type cho node
    if($n_parent == 0 && $n_child > 0)
    {
        $node_color = $color_root;
        $node_class = 'root';
    }
    elseif($n_parent > 0 && $n_child >0)
    {
        $node_color = $color_bridge;
        $node_class = 'bridge';
    }
    elseif($n_parent > 0 && $n_child == 0)
    {
        $node_color = $color_leaf;
        $node_class = 'leaf';
    }
    elseif($n_parent == 0 && $n_child == 0)
    {
        $node_color = $color_alone;
        $node_class = 'alone';
    }
    $dropcheck_items .=  "<option selected='' class='".$node_class."' id='item_".$r->subject_id."' style='color:".$node_color."' value='".$r->subject_id."'>".$r->subject_name_vn."</option>";
    
    //save node data
    $url = 'matching_result.php?id_bbsurvey='.$id_bbsurvey.'&id_subject='.$r->id;
    $node_data .= "node_data['".$r->subject_id."'] = {id:'".$r->id."',color:'".$node_color."',shape:'block',label:'".$r->subject_id."',name:'".$r->subject_name_vn."',desc:'".$r->subject_id." : ".$r->subject_name_vn."',selected:true,color_selected:'".$color_selected."',link:'".$url."',type:'subject_node'};";
}
?>
<div id='subject_desc' style="float: left;">
            <b></a><div id="desc"></div></b>
        </div>
        <div id='subject_filter' style="float: right;">
        <select id="drop" multiple="multiple" style="display: none;">
                <?php echo '<option align="left">'.get_string('all_subject', 'local_blackboxsurvey').'</option>'.$dropcheck_items; ?>
            </select>
        </div>
<div>
<div align="center"><canvas id="viewport"></canvas></div>
<table id="color_desc">
    <tr>
        <td id="td_root" onclick="filter_by_color(this,'root');" style="cursor:pointer;background-color: <?php echo $color_root;?>;" class="icon_desc">&nbsp&#10004</td>
        <td style="color: <?php echo $color_root;?>;" class="text_desc"><?php echo get_string('root_subject', 'local_blackboxsurvey');?></td>
        
        <td id="td_bridge" onclick="filter_by_color(this,'bridge');" style="cursor:pointer;background-color: <?php echo $color_bridge;?>;" class="icon_desc">&nbsp&#10004</td>
        <td style="color: <?php echo $color_bridge;?>;" class="text_desc"><?php echo get_string('bridge_subject', 'local_blackboxsurvey');?></td>
        
        <td id="td_leaf" onclick="filter_by_color(this,'leaf');" style="cursor:pointer;background-color: <?php echo $color_leaf;?>;" class="icon_desc">&nbsp&#10004</td>
        <td style="color: <?php echo $color_leaf;?>;" class="text_desc"><?php echo get_string('leaf_subject', 'local_blackboxsurvey');?></td>
        
        <td id="td_problem" onclick="filter_by_color(this,'problem');" style="cursor:pointer;background-color: <?php echo $color_problem;?>;" class="icon_desc">&nbsp&#10004</td>
        <td style="color: <?php echo $color_problem;?>;" class="text_desc"><?php echo get_string('problem_subject', 'local_blackboxsurvey');?></td>
        
        <td id="td_alone" onclick="filter_by_color(this,'alone');" style="cursor:pointer;background-color: <?php echo $color_alone;?>;" class="icon_desc">&nbsp&#10004</td>
        <td style="color: <?php echo $color_alone;?>;" class="text_desc"><?php echo get_string('alone_subject', 'local_blackboxsurvey');?></td>
        
        <td class="icon_desc " style="border: 2px solid <?php echo $color_selected;?> !important;"></td>
        <td style="color: <?php echo $color_selected;?>;" class="text_desc"><?php echo get_string('selected_subject', 'local_blackboxsurvey');?></td>
    </tr>
</table>
<div style="display: none;">
    <input id="ck_root" class="filter_color" type="checkbox" value="root" checked=""/>
    <input id="ck_bridge" class="filter_color" type="checkbox" value="bridge" checked=""/>
    <input id="ck_leaf" class="filter_color" type="checkbox" value="leaf" checked=""/>
    <input id="ck_problem" class="filter_color" type="checkbox" value="problem" checked=""/>
    <input id="ck_alone" class="filter_color" type="checkbox" value="alone" checked=""/>
</div>
</div>
<script language="javascript" type="text/javascript">

window.onload = window.onresize = function() {
    canvas = document.getElementById("viewport");
    canvas.width = document.body.clientWidth - 30;
    canvas.height = document.body.clientHeight - 60;
}
var sys = arbor.ParticleSystem(1000, 400,1);
sys.parameters({stiffness:900, repulsion:2000, gravity:true, dt:0.015})
sys.renderer = Renderer("#viewport") ;
//save subject node data
var node_data = {};
//save child data cua 1 subject
var child_data = {};
//save parent data cua 1 subject
var parent_data = {};
var ancestors = {};
var child_link_node = {};
var num_relation = {};
<?php
//show course map
echo $node_data;
echo $child_data;
echo $parent_data;
echo $child_link_node;
echo $num_relation;
?>
function filter_by_color(ths,type)
{
    if ( $('#ck_'+type).prop('checked')) 
    {
        $('#ck_'+type).prop('checked', false);
        $(ths).html('');
    }
    else 
    {
        $('#ck_'+type).prop('checked', true);
        $(ths).html('&nbsp&#10004');
    }
    var count = 0;
    $("#drop option").each(function()
    {
        var myClass = $(this).prop("class");
        if($('#ck_'+myClass).prop('checked'))
        {
            if(myClass == type)
                $(this).prop('selected', true);
        }
        else
            $(this).prop('selected', false);
    });
    //update filter list
    $("#drop").dropdownchecklist("refresh");
    //draw course map
    var subject_list = document.getElementById("drop");
    draw_course_map(subject_list);
}

function save_ancestors_list(index, the_sub)
{
    for(var idx in parent_data[the_sub])
    {
        //if(parent_data[the_sub][idx] != index && ancestors[index][parent_data[the_sub][idx]] != true)
        if(ancestors[index][parent_data[the_sub][idx]] != true)
        {
            ancestors[index][parent_data[the_sub][idx]] = true;
            save_ancestors_list(index,parent_data[the_sub][idx]);
        }
    }
}

function create_ancestors_list(selector)
{
    for( m = 1; m < selector.options.length; m++ )
    {
        if(parent_data[selector.options[m].value].length > 0)
        {
            ancestors[selector.options[m].value] = {};
            save_ancestors_list(selector.options[m].value,selector.options[m].value);
            if(ancestors[selector.options[m].value] != null && ancestors[selector.options[m].value][selector.options[m].value] == true)
            {
                //ser problem color for subject
                node_data[selector.options[m].value].color = '<?php echo $color_problem;?>';
                $('#item_'+selector.options[m].value).css('color','<?php echo $color_problem;?>')
                $('#item_'+selector.options[m].value).prop("class","problem");
            }
        }
    }
}

function draw_course_map(selector)
{
    //sys.prune(function(node, from, to){return true;});
    var node_array = {};
    var count_node = 0;
    var first_node = null;
    
    //uncheck all color filter
    $('.filter_color').each(function(){
        $('#ck_'+$(this).val()).prop('checked', false);
        $('#td_'+$(this).val()).html('');
    });
    //show relating subject
	for( i = 1; i < selector.options.length; i++ ){
		if (selector.options[i].selected){
		    var node_idx = selector.options[i].value;
            var n_child = child_data[node_idx].length;
            var n_parent = parent_data[node_idx].length;
            //set check color filter
            var myClass = $('#item_'+node_idx).prop("class");
            $('#ck_' + myClass).prop('checked', true);    
            $('#td_' + myClass).html('&nbsp&#10004');
            //draw subject node
            //set selected for selected node
            node_data[node_idx].selected = true;
            first_node = node_array[node_idx] = sys.addNode(node_idx,node_data[node_idx]);
            count_node++;  
            //child nodes
            for( j = 0; j < n_child; j++ )
            {
                var child_node_idx = child_data[node_idx][j];
                //draw node if not exist
                if(node_array[child_node_idx] == null)
                {
                    node_data[child_node_idx].selected = false;
                    node_array[child_node_idx] = sys.addNode(child_node_idx,node_data[child_node_idx]);
                    count_node++;
                }
                //draw child node relationship
                var temp_color = '';
                if(ancestors[node_idx] != null && ancestors[node_idx][child_node_idx] == true)//kiem tra relationship co bi loop ko
                    temp_color = '<?php echo $color_problem;?>';
                else
                    temp_color = '<?php echo $color_edge;?>';
                var url = 'view_relationship.php?id_bbsurvey='+'<?php echo $id_bbsurvey;?>'+'&id_from='+node_data[node_idx].id+'&id_to='+node_data[child_node_idx].id;
                var str_desc = node_data[node_idx].name + " >> " + node_data[child_node_idx].name;
                var n_rel = '('+ num_relation[node_idx+child_node_idx] +')';
                var temp_node = sys.addNode(node_idx+child_node_idx,{"color":'white', "shape":"dot", "from":node_idx, "to":child_node_idx, "link":url, "desc":str_desc, "type":'link_node', "label":n_rel, "textcolor":'black'});
                sys.addEdge(node_array[node_idx],temp_node,{color:temp_color});
                sys.addEdge(temp_node,node_array[child_node_idx],{directed:{edge:"->"},color:temp_color});
            }
            //parent nodes
            for( k = 0; k < n_parent; k++ )
            {
                var parent_node_idx = parent_data[node_idx][k];
                //draw node if not exist
                if(node_array[parent_node_idx] == null)
                {
                    node_data[parent_node_idx].selected = false;
                    node_array[parent_node_idx] = sys.addNode(parent_node_idx,node_data[parent_node_idx]);
                    count_node++;
                }
                //draw parent node relationship
                var temp_color = '';
                if(ancestors[parent_node_idx] != null && ancestors[parent_node_idx][node_idx] == true)//kiem tra relationship co bi loop ko
                    temp_color = '<?php echo $color_problem;?>';
                else
                    temp_color = '<?php echo $color_edge;?>';
                var url = 'view_relationship.php?id_bbsurvey='+'<?php echo $id_bbsurvey;?>'+'&id_from='+node_data[parent_node_idx].id+'&id_to='+node_data[node_idx].id;
                var str_desc = node_data[parent_node_idx].name + " >> " + node_data[node_idx].name;
                var n_rel = '('+ num_relation[parent_node_idx+node_idx] +')';
                var temp_node = sys.addNode(parent_node_idx+node_idx,{"color":'white', "shape":"dot", "from":parent_node_idx, "to":node_idx, "link":url, "desc":str_desc, "type":'link_node', "label":n_rel, "textcolor":'black'});
                sys.addEdge(node_array[parent_node_idx],temp_node,{color:temp_color});
                sys.addEdge(temp_node,node_array[node_idx],{directed:{edge:"->"},color:temp_color});
            }
            
		}
	}
    //remove the unrelated subject
    for( i = 1; i < selector.options.length; i++ ){
        var index = selector.options[i].value;
        if(node_array[index] == null)
        {
            if(sys.getNode(index) != null)
            {
                sys.pruneNode(index);
            }
        }
    }
    //remove link node
    for( i = 1; i < selector.options.length; i++ )
    {
        var index = selector.options[i].value;
        for(var cln in child_link_node[index])
        {
            var xxx = sys.getNode(child_link_node[index][cln]);
            if(xxx != null)
            {
                if((sys.getNode(xxx.data.from) == null || sys.getNode(xxx.data.to) == null) || (node_data[xxx.data.from].selected == false && node_data[xxx.data.to].selected == false))
                    sys.pruneNode(child_link_node[index][cln]);  
            } 
        }
    }
    //spacial case if displaying only one subject
    if(count_node == 1)
    {
        var alert = sys.addNode('alert',{color:"red","shape":"block",label:"No connection to other subjects",link:""});
        sys.addEdge(first_node,alert,{directed:{edge:"->"}}); 
    }
    else if(sys.getNode('alert') != null)
        sys.pruneNode('alert');
}

$(document).ready(function() {
    var subject_list = document.getElementById("drop");
    //create ancestors list
    create_ancestors_list(subject_list);
    //draw course map
    draw_course_map(subject_list);
    
    $("#drop").dropdownchecklist({ 
        maxDropHeight: document.body.clientHeight - 30,
        firstItemChecksAll: true,
        textFormatFunction: function(options) {
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch(countOfSelected) {
               case 0: return "<b><?php echo get_string('choose_subject', 'local_blackboxsurvey');?></b>";
               case 1: return selectedOptions.text();
               case options.size(): return "<b><?php echo get_string('all_subject', 'local_blackboxsurvey');?></b>";
               default: return countOfSelected + " <?php echo get_string('selected_subject', 'local_blackboxsurvey');?>";
            }
        },
        //update course map
        onComplete: function(selector){
            draw_course_map(selector);
	   } 
    });
});
</script>
</body>
</html>